import { Injectable } from '@nestjs/common';
import { CreatePlayWithDto } from './dto/create-play-with.dto';
import { UpdatePlayWithDto } from './dto/update-play-with.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { ILike, Repository } from 'typeorm';
import { PlayWith } from './entities/play-with.entity';
import { loadPageQueryResult } from 'src/utils/utils';
import { uid } from 'uid';

@Injectable()
export class PlayWithService {
  constructor(@InjectRepository(PlayWith) private readonly playWithRepository: Repository<PlayWith>,) { }

  //新增
  async create(createPlayWithDto: CreatePlayWithDto) {
    await this.playWithRepository.save({ ...createPlayWithDto, playWithId: uid() });
    return {
      code: 1,
      message: '创建成功'
    };
  }

  //分页查询
  async findAll(pageNum: number, pageSize: number, playWithName: string) {
    let res = await this.playWithRepository.findAndCount({
      where: {
        playWithName: playWithName ? ILike(`%${playWithName}%`) : undefined
      },
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
      order: { id: 'DESC' }
    })

    return {
      code: 1,
      data: loadPageQueryResult<[PlayWith[], number]>(res, pageNum, pageSize)
    };
  }
  //详情
  async findOne(playWithId: string) {
    let res = await this.playWithRepository.findOne({
      where: {
        playWithId: playWithId
      }
    })
    return {
      code: 1,
      data: res
    }
  }
  //更新陪玩数据
  async update(playWithId: string, updatePlayWithDto: UpdatePlayWithDto) {
    await this.playWithRepository.update({ playWithId: playWithId }, { ...updatePlayWithDto })
    return {
      code: 1,
      message: '更新成功'
    }
  }
  //删除
  async remove(playWithId: string) {
    await this.playWithRepository.delete({ playWithId })
    return {
      code: 1,
      message: '删除成功'
    }
  }
}
